#-*-coding:utf-8-*-
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.utils.html import mark_safe
from django.core.paginator import *
from django.db.models import Q, F
from django.views.generic import View


import time, hmac, hashlib, json, os


from models import TerminalUser
from Assets.models import Server, IpAddress
from ITAdmin.settings import GATEONE_SERVER, GATEONE_SECRET, GATEONE_API_KEY, GATEONE_USER_DIR
from Users.models import UserProfile
from .task import send_ras_key
from utils.rsa import gen_keys
from  utils.constant import ACTIVED
from utils.view import get_params


# Create your views here.


class TerminalUserView(View):
    def get(self, request):
        if request.user.is_authenticated():
            terminals = TerminalUser.objects.all()
            search, start, end, entry, num = get_params(request)
            context = {'ssh': ACTIVED,
                       'terminaluser': ACTIVED,
                       'entry': entry,
                       'num': num,
                       'table_class': mark_safe('table table-bordered'),
                       'table_title': u'连接用户'}
            if not terminals.exists():
                return render(request, 'Terminal/terminaluser.html', context=context)
            if not search:
                paginator = Paginator(terminals, entry)
                terminals = paginator.page(num)
                context['objects'] = terminals
            else:
                terminals.filter(Q(user__username__icontains=search)|Q(servers__name__icontains=search))
                paginator = Paginator(terminals, entry)
                terminals = paginator.page(num)
                context['objects'] = terminals
                context['entry'] = entry
                context['search'] = 'top-search=' + search
            return render(request, 'Terminal/terminaluser.html',context=context)
        else:
            return HttpResponseRedirect("/")


class AddTerminalUser(View):
    def get(self, request):
        user_id = request.GET.get('user_id')
        users = UserProfile.objects.all()
        servers = Server.objects.all()
        context = {'users': users, 'servers': servers, 'ssh': ACTIVED, 'terminaluser': ACTIVED}
        if user_id:
            context['selected_user'] = user_id
            selected_servers = list()
            servers = TerminalUser.objects.filter(user_id=user_id).values('servers__id').all()
            for server in servers:
                selected_servers.append(server['servers__id'])
            context['selecetd_servers'] = selected_servers
        return render(request, 'Terminal/adduser.html', context=context)

    def post(self, request):
        if request.user.is_authenticated():
            if request.user.has_perm('Terminal.add_terminaluser'):
                user =  request.POST.get('user')
                username = UserProfile.objects.get(id=user).username
                server_ids =  json.loads(request.POST.get('servers'))
                path = GATEONE_USER_DIR + username + '/.ssh'
                try:
                    if not os.path.exists(path):
                        os.makedirs(path)
                        gen_keys(username, path)
                    terminal = TerminalUser.objects.filter(user_id=user)
                    if not terminal.exists():
                        terminal = TerminalUser(user_id=user)
                        terminal.save()
                    else:
                        terminal = terminal.first()
                    terminal.servers.clear()
                    servers = Server.objects.filter(Q(id__in=server_ids) &
                                          Q(id=F('ipaddress__server__id')) &
                                          Q(ipaddress__type=1)).values('id','ipaddress__ip', 'ssh_port', 'password').all()
                    for server in servers:
                        terminal.servers.add(server['id'])
                        send_ras_key.delay(hostname=server['ipaddress__ip'], path=path, username='root', password=server['password'],
                                           port=server['ssh_port'])
                    return JsonResponse({'status': 1})
                except Exception as e:
                    return JsonResponse({'status': 0, 'msg': e.message})
            else:
                return HttpResponse(status=403)
        else:
            return HttpResponseRedirect('/')



class TerminalView(View):
    def get(self, request):
        if request.user.is_authenticated():
            search, start, end, entry, num = get_params(request)
            context = {'ssh': ACTIVED, 'terminal': ACTIVED, 'entry': entry, 'table_class': mark_safe('table table-striped'), 'table_title': u'可连接主机'}
            user = TerminalUser.objects.filter(user_id=request.user.id)
            if not user.exists():
                return render(request, 'Terminal/terminal.html', context=context)
            servers = user.first().servers.all()
            if not search:
                paginator = Paginator(servers, entry)
                servers = paginator.page(num)
                context['objects'] = servers
            else:
                servers = servers.filter(Q(name__icontains=search) |
                                         Q(cpu__name__icontains=search) |
                                         Q(generatorroom__name__icontains=search))
                paginator = Paginator(servers, entry)
                servers = paginator.page(num)
                context['objects'] = servers
                context['search'] = 'top-search=' + search
                context['last_search'] = search
            return render(request, 'Terminal/terminal.html', context=context)
        else:
            return HttpResponseRedirect('/')


class ConnectView(View):
    def get(self, request):
        if request.user.is_authenticated():
            host_ip = request.GET.get('host', None)
            host_user = request.GET.get('user', 'root')
            host_port = request.GET.get('port')
            host_name = request.GET.get('server')
            return render(request, 'Terminal/connect.html', {'host_ip': host_ip,
                                                             'host_user': host_user,
                                                             'host_port': host_port,
                                                             'host_name': host_name,
                                                             'terminal': mark_safe('class="active"'),
                                                             'ssh': mark_safe('class="active"')})
        else:
            return HttpResponseRedirect('/')


def generate_gate_one_auth_obj(request):
    if request.user.is_authenticated():
        user = request.user.username
        gateone_server = GATEONE_SERVER
        secret = GATEONE_SECRET
        api_key = GATEONE_API_KEY
        authobj = {
            'api_key': api_key,
            'upn': user,
            'timestamp': str(int(time.time() * 1000)),
            'signature_method': 'HMAC-SHA1',
            'api_version': '1.0'
        }
        my_hash = hmac.new(secret, digestmod=hashlib.sha1)
        my_hash.update(authobj['api_key'] + authobj['upn'] + authobj['timestamp'])
        authobj['signature'] = my_hash.hexdigest()
        auth_info_and_server = {"url": gateone_server, "auth": authobj}
        valid_json_auth_info = json.dumps(auth_info_and_server)
        return HttpResponse(valid_json_auth_info)
    else:
        return HttpResponse(status=403)


def del_terminal_user(request):
    if request.user.is_authenticated():
        if request.user.has_perm('Terminal.add_terminaluser'):
            user_id = request.POST.get('user_id')
            try:
                TerminalUser.objects.filter(user_id=user_id).delete()
                return JsonResponse({'status': 1})
            except Exception as e:
                return JsonResponse({'status': 0, 'msg': e.message})
        else:
            HttpResponse(status=403)
    else:
        HttpResponseRedirect('/')
